﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml.Serialization;

namespace Century.Common
{
    public class XMLHelper
    {

        /// <summary>
        /// Method To Serialize an objectan to an XML stream with Unicode Encoding
        /// </summary>
        /// <typeparam name="T">Type of object</typeparam>
        /// <param name="objForSerialization">XML stream to serialize</param>
        /// <returns>XML String</returns>
        public static string Serialize<T>(T objForSerialization) where T : new()
        {
            return Serialize<T>(objForSerialization, Encoding.Unicode);
        }

        /// <summary>
        /// Method To Serialize an objectan to an XML stream
        /// </summary>
        /// <typeparam name="T">Type of object</typeparam>
        /// <param name="streamObject">XML stream to serialize</param>
        /// <param name="encoding">Encoding of Serialization</param>
        /// <returns>XML String</returns>
        /// <summary>
        public static string Serialize<T>(T objForSerialization, Encoding encoding) where T : new()
        {
            MemoryStream ms = new MemoryStream();
            XmlSerializer serializer = new XmlSerializer(typeof(T));
            serializer.Serialize(ms, objForSerialization);
            ms.ToArray().ToString(encoding);
            return string.Empty;
        }

        /// <summary>
        ///  Method To Deserialize an XML string to an object with Unicode Encoding
        /// </summary>
        /// <typeparam name="T">Type of object</typeparam>
        /// <param name="streamObject">XML String</param>
        /// <returns>Deserialized object</returns>
        public static T Deserialize<T>(string xmlString) where T : new()
        {
            return Deserialize<T>(xmlString, Encoding.Unicode);
        }

        /// <summary>
        /// Method To Deserialize an XML string to an object
        /// </summary>
        /// <typeparam name="T">Type of object</typeparam>
        /// <param name="xmlString">XML String</param>
        /// <param name="encoding">Encoding of Deserialization</param>
        /// <returns>Deserialized object</returns>
        public static T Deserialize<T>(string xmlString, Encoding encoding) where T : new()
        {
            byte[] buffer = xmlString.ToByteArray(encoding);
            MemoryStream ms = new MemoryStream(buffer);
            ms.Position = 0;
            XmlSerializer serializer = new XmlSerializer(typeof(T));
            T objForSerialization = (T)serializer.Deserialize(ms);
            ms.Close();
            return objForSerialization;
        }
    }
}
